#!/bin/bash

KEYNAME=keyname

HOSTEDZONEID=Z00000000000

NAME=hostname.com.

EXTERNALIPSOURCE=http://ip.minivi.com

XMLCREATE=$(/bin/mktemp)

TTL=300

IPADDR=$(/usr/bin/curl -4 -s "$EXTERNALIPSOURCE")

CURRENTRECORD=$(~/dnscurl.pl --keyname "$KEYNAME" -- -H "Content-Type: text/xml; charset=UTF-8" -X GET "https://route53.amazonaws.com/2012-12-12/hostedzone/$HOSTEDZONEID/rrset?name=$NAME&type=A&maxitems=1")

CURRENTTTL=$(echo "$CURRENTRECORD" | grep TTL | sed 's|.*<TTL>\([^<]*\)</TTL>.*|\1|')

CURRENTVALUE=$(echo "$CURRENTRECORD" | grep ResourceRecord | sed 's|.*<ResourceRecord><Value>\([^<]*\)</Value></ResourceRecord>.*|\1|')

/bin/cat <<EOF > "$XMLCREATE"
<?xml version="1.0" encoding="UTF-8"?>
<ChangeResourceRecordSetsRequest xmlns="https://route53.amazonaws.com/doc/2012-12-12/">
   <ChangeBatch>
      <Changes>
         <Change>
            <Action>DELETE</Action>
            <ResourceRecordSet>
               <Name>${NAME}</Name>
               <Type>A</Type>
               <TTL>${CURRENTTTL}</TTL>
               <ResourceRecords>
                  <ResourceRecord>
                     <Value>${CURRENTVALUE}</Value>
                  </ResourceRecord>
               </ResourceRecords>
            </ResourceRecordSet>
         </Change>
         <Change>
            <Action>CREATE</Action>
            <ResourceRecordSet>
               <Name>${NAME}</Name>
               <Type>A</Type>
               <TTL>${TTL}</TTL>
               <ResourceRecords>
                  <ResourceRecord>
                     <Value>${IPADDR}</Value>
                  </ResourceRecord>
               </ResourceRecords>
            </ResourceRecordSet>
         </Change>
      </Changes>
   </ChangeBatch>
</ChangeResourceRecordSetsRequest>
EOF

~/dnscurl.pl --keyname "$KEYNAME" -- -H "Content-Type: text/xml; charset=UTF-8" -X POST --upload-file "$XMLCREATE" "https://route53.amazonaws.com/2012-12-12/hostedzone/$HOSTEDZONEID/rrset"

/bin/rm -f "$XMLCREATE"

